package com.ch04.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 *@ClassName MyBatisSqlSessionFactory
 *@Description  TODO
 *@Author Kx
 *@Date 2025/4/21 20:18
 *@Version 1.0
 */
public class MyBatisSqlSessionFactory {
    // 声明一个静态变量sqlSessionFactory，用于创建SqlSession
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            // 读取配置文件mybatis-config.xml获取对象实例,使用单例模式确保唯一性,减少资源
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");

            //通过SqlSessionFactoryBuilder类来解析流的数据并初始化
            //SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /***
     * @author: kx
     * @date: 2025/4/23 16:15
     * @param flag : 是否自动提交事务
     * @return org.apache.ibatis.session.SqlSession
     * @description: 创建SqlSession对象  如果autoCommit设置为true，则表示自动提交
    */
    public static SqlSession getSqlSession(boolean flag) {
        return sqlSessionFactory.openSession(flag);
    }


    /*** 
     * @author: kx
     * @date: 2025/4/23 16:15
     * @return org.apache.ibatis.session.SqlSession
     * @description: 默认获取自动提交事务的SqlSession
    */
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(true);
    }
}
